#coding=utf-8
import cv2
import numpy as np  
from matplotlib import pyplot as plt
import copy

def myHough(img):
    # binary image
    ret,otsu_bin = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    
    #gray image
#     otsu_bin = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    
    #canny
    edges = cv2.Canny(otsu_bin,50,200)    
    # hough
    lines = cv2.HoughLines(edges,1,np.pi/180,80)
    ret_img=copy.deepcopy(img)
    
    print type(img)
    print type(ret_img)
    print type(lines)
    print lines

    #提取为为二维
    lines1 = lines[:,0,:]
    for rho,theta in lines1[:]: 
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a*rho
        y0 = b*rho
        x1 = int(x0 + 1000*(-b))
        y1 = int(y0 + 1000*(a))
        x2 = int(x0 - 1000*(-b))
        y2 = int(y0 - 1000*(a)) 
        # drawing
        cv2.line(ret_img,(x1,y1),(x2,y2),255,3)

    return otsu_bin,edges,ret_img


def myHoughP(img):
    # binary image
    ret,otsu_bin = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    
    #gray image
#     otsu_bin = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    
    #canny
    edges = cv2.Canny(otsu_bin,50,200)    
    # hough
    lines = cv2.HoughLinesP(edges,1,np.pi/180,80,minLineLength=60,maxLineGap=10)
    ret_img=copy.deepcopy(img)
    
    print type(img)
    print type(ret_img)
    print type(lines)
    print lines

    #提取为为二维
    lines1 = lines[:,0,:]
    for x1,y1,x2,y2 in lines1[:]: 
        # drawing
        cv2.line(ret_img,(x1,y1),(x2,y2),255,3)

    return otsu_bin,edges,ret_img


def myHoughCircle(img):
#     ret,otsu_bin = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    ret_img=copy.deepcopy(img)
    circles1 = cv2.HoughCircles(gray,cv2.HOUGH_GRADIENT,1,100,param1=100,param2=30,minRadius=150,maxRadius=160)
    circles = circles1[0,:,:]#提取为二维
    circles = np.uint16(np.around(circles))#四舍五入，取整
    
    for i in circles[:]: 
        cv2.circle(ret_img,(i[0],i[1]),i[2],(255,0,0),5)#画圆
        cv2.circle(ret_img,(i[0],i[1]),2,(255,0,255),10)#画圆心
        
    return ret_img

if __name__ == '__main__':
#     Hough()
    img1 = cv2.imread("..\\img\\iris.jpg",-1)
    img2 = cv2.imread("..\\img\\eye.jpg",-1)
#     otsu_bin,edges,ret_img=myHoughP(img1)
    ret_img=myHoughCircle(img2)


#     cv2.imshow("img",img2)
    plt.subplot(211), plt.imshow(img2), plt.title('Original Fourier') 
    plt.subplot(212),plt.imshow(ret_img),plt.title('ret_img')
#     plt.xticks([]),plt.yticks([])
    plt.show()
    print 'over'

